<?php

/**
 * Created by PhpStorm.
 * Script Name: MsgLog.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\admin\model\BotGroupmember;
use app\admin\model\BotMember;
use app\common\model\MsgLog as MsgLogM;
use app\common\model\MsgGather as GatherM;
use app\common\service\MsgGather as GatherService;
use app\constants\Bot as BotConst;
use app\constants\Common;

class Msglog extends Botbase
{
    /**
     * @var MsgLogM
     */
    protected $model;
    /**
     * @var GatherM
     */
    protected $gatherM;
    /**
     * @var BotGroupmember
     */
    private $groupMemberM;
    /**
     * @var BotMember
     */
    private $memberM;
    /**
     * @var array
     */
    private $tabList;


    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new MsgLogM();
        $this->groupMemberM = new BotGroupmember();
        $this->memberM = new BotMember();
        $this->gatherM = new GatherM();
        $this->tabList = [
            'index' => ['title' => '消息列表', 'href' => url('index')],
            'rule' => ['title' => '存档规则', 'href' => url('rule')],
            'group' => ['title' => '存档规则分组', 'href' => url('msggathergroup/index')],
        ];
    }

    /**
     *
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        $year = input('year', date('Y'));
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['bot_id' => $this->bot['id'], 'year' => $year];
            $search_key = input('search_key', '');
            $search_key && $where['from_wxid|from_nickname|group_wxid|group_nickname'] = ['like', "%{$search_key}%"];
            $msg_type = input('msg_type', 0);
            $msg_type && $where['msg_type'] = $msg_type;
            isset($post_data['gather_id']) && $post_data['gather_id'] != -1 && $where['gather_id'] = $post_data['gather_id'];
            if(!empty($post_data['create_time'])){
                $times = explode('~', $post_data['create_time']);
                $where['create_time'] = ['between', [strtotime($times[0]), strtotime($times[1])]];
            }
            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList([$post_data['page'], $post_data['limit']], $where, ['id' => 'desc'], true, true);
                foreach ($list as $k => $item){
                    switch ($item['msg_type']){
                        case BotConst::MSG_APP:
                            $item['content'] = '<xmp>'.$item['content'].'</xmp>';
                            break;
                    }
                    $item['msg_type'] = BotConst::msgTypes($item['msg_type']);
                    $list[$k] = $item;
                }
            }else{
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList, __FUNCTION__)
            ->setSearch([
                ['type' => 'select', 'name' => 'gather_id', 'title' => '所属规则', 'options' => [-1=>'全部'] + GatherService::getSelectList($this->adminInfo['id'], $this->bot['id'])],
                ['type' => 'select', 'name' => 'msg_type', 'title' => '内容类型', 'options' => [0=>'全部'] + BotConst::msgTypes()],
                ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', "placeholder" => '好友昵称、wxid、群昵称、群wxid搜索'],
                ['type' => 'datetime_range', 'name' => 'create_time', 'title' => '消息时间', "placeholder" => '消息时间']
            ])
                ->addTableColumn(['title' => 'msgid', 'field' => 'msg_id', 'minWidth' => 70])
                ->addTableColumn(['title' => '内容类型', 'field' => 'msg_type','minWidth' => 70])
                ->addTableColumn(['title' => '内容', 'field' => 'content', 'type' => 'article','minWidth' => 200])
                ->addTableColumn(['title' => '发信人昵称', 'field' => 'from_nickname', 'minWidth' => 80])
                ->addTableColumn(['title' => '发信人wxid', 'field' => 'from_wxid', 'minWidth' => 100])
                ->addTableColumn(['title' => '群昵称', 'field' => 'group_nickname', 'minWidth' => 80])
                ->addTableColumn(['title' => '群wxid', 'field' => 'group_wxid', 'minWidth' => 100])
                ->addTableColumn(['title' => '时间', 'field' => 'create_time',  'type' => 'datetime', 'minWidth' => 180]);
        return $builder->show();
    }

    /**
     * 保存规则
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function rule()
    {
        //dump(GatherService::searchData(['bot_id' => $this->bot['id'], 'status' => 1], true));exit;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['bot_id' => $this->bot['id']];
            $total = $this->gatherM->total($where, true);
            if ($total) {
                $list = $this->gatherM->getList([$post_data['page'], $post_data['limit']], $where, [], true, true);
                $groups = GatherService::getGroupSelectList($this->adminInfo['id'], $this->bot['id']);
                foreach ($list as $k => $v){
                    if($v['msg_types']){
                        $types = explode(',', $v['msg_types']);
                        $type_arr = [];
                        foreach ($types as $t){
                            $type_arr[] = BotConst::msgTypes($t);
                        }
                        $v['msg_types'] = implode(',', $type_arr);
                    }
                    if($v['wxids']){
                        $ids = explode(',', $v['wxids']);
                        if($member = model('admin/botMember')->getOneByMap([
                            'wxid' => $ids[0]
                        ])){
                            $v['wxids'] = $member['nickname'];
                            if(count($ids) > 1){
                                $v['wxids'] .= "等".count($ids)."个对象";
                            }
                        }
                    }else if(! empty($v['member_tags'])){
                        $v['wxids'] = '用户分组：' . $v['member_tags'];
                    }
                    $v['to_media'] = Common::yesOrNo(intval($v['to_media']));
                    $v['group_title'] = $groups[$v['group_id']] ?? '';
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
        $builder = new ListBuilder();
        $builder->addTopButton('addnew', ['title' => '新增规则'])
            ->setTabNav($this->tabList, __FUNCTION__)
            ->addTableColumn(['title' => 'ID', 'field' => 'id', 'minWidth' => 70])
            ->addTableColumn(['title' => '分组', 'field' => 'group_title', 'minWidth' => 100])
            ->addTableColumn(['title' => '规则名称', 'field' => 'title', 'minWidth' => 100])
            ->addTableColumn(['title' => '接收对象', 'field' => 'wxids', 'minWidth' => 200])
            ->addTableColumn(['title' => '内容格式', 'field' => 'msg_types', 'minWidth' => 100])
            ->addTableColumn(['title' => '监听关键词', 'field' => 'keyword', 'minWidth' => 100])
            ->addTableColumn(['title' => '是否转存到素材库', 'field' => 'to_media', 'minWidth' => 80])
            ->addTableColumn(['title' => '有效期', 'field' => 'expire_time', 'type'=>'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'enum', 'options' => Common::status(), 'minWidth' => 60])
            ->addTableColumn(['title' => '操作', 'minWidth' => 100, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete');
        return $builder->show();
    }

    public function add(){
        $data = ['bot_id' => $this->bot['id'], 'status' => 1, 'to_media' => 0];
        $groups = GatherService::getGroupSelectList($this->adminInfo['id'], $this->bot['id']);

        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('bot_id', 'hidden', 'bot_id', 'bot_id')
            ->addFormItem('group_id', 'chosen', '分组', '分组', $groups)
            ->addFormItem('title', 'text', '规则名称', '规则名称',[], 'maxlength=150')
            ->addFormItem('status', 'radio', '状态', '状态', Common::status(), 'required')
            ->addFormItem('msg_types', 'chosen_multi', '消息类型', '选择需要保存的消息类型', BotConst::msgTypes(), 'required')
            ->addFormItem('keyword', 'text', '监控关键词', '针对文本类型监控关键词',[], 'maxlength=150')
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('member_tags', 'chosen_multi', '用户分组', '用户分组', model('memberTag')->getTitleToTitle($this->bot['id']))
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '若填此项则用户分组的设置将失效', $this->getMembers())
            ->addFormItem('to_media', 'radio', '转存素材库', '目前支持转存类型为：文本、图片、文件、视频、小程序卡片', Common::yesOrNo(), 'required')
            ->addFormItem('expire_time', 'datetime', '过期时间', '不填则默认一直生效')
            ->setFormData($data);
        return $builder->show();
    }

    public function edit(){
        $id = input('id', null);
        $data = $this->gatherM->getOneByMap([
            'bot_id' => $this->bot['id'],
            'id' => $id
        ], true, true);

        if (!$data) {
            $this->error('参数错误');
        }

        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $data['member_tags'] = empty($data['member_tags']) ? [] : explode(',', $data['member_tags']);
        $data['msg_types'] = empty($data['msg_types']) ? [] : explode(',', $data['msg_types']);
        $groups = GatherService::getGroupSelectList($this->adminInfo['id'], $this->bot['id']);

        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('group_id', 'chosen', '分组', '分组', $groups)
            ->addFormItem('title', 'text', '规则名称', '规则名称',[], 'maxlength=150')
            ->addFormItem('status', 'radio', '状态', '状态', Common::status(), 'required')
            ->addFormItem('msg_types', 'chosen_multi', '消息类型', '选择需要保存的消息类型', BotConst::msgTypes(), 'required')
            ->addFormItem('keyword', 'text', '监控关键词', '针对文本类型监控关键词',[], 'maxlength=150')
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('member_tags', 'chosen_multi', '用户分组', '用户分组', model('memberTag')->getTitleToTitle($this->bot['id']))
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '若填此项则用户分组的设置将失效', $this->getMembers())
            ->addFormItem('to_media', 'radio', '转存素材库', '目前支持转存类型为：文本、图片、文件、视频、小程序卡片', Common::yesOrNo(), 'required')
            ->addFormItem('expire_time', 'datetime', '过期时间', '不填则默认一直生效')
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $post_data = input('post.');
        $post_data['admin_id'] = $this->adminInfo['id'];
        $this->model = $this->gatherM;
        !empty($post_data['expire_time']) && $post_data['expire_time'] = strtotime($post_data['expire_time']);
        if(empty($post_data[$this->pk])){
            $res = $this->model->addOne($post_data);
        }else {
            $res = $this->model->updateOne($post_data);
        }
        if($res){
            GatherService::searchData(['bot_id' => $res['bot_id']], true);
            $this->success('数据保存成功', $jump_to);
        }else{
            $this->error('数据保存出错');
        }
    }

    public function setStatus()
    {
        $this->model = $this->gatherM;
        parent::setStatus(); // TODO: Change the autogenerated stub
    }
}